Explore various methods for generating output in JavaScript with clear examples. Each example shows the code and its output below.
console.log()
- For DebuggingThis method outputs information to the console, useful for debugging or viewing data in development tools.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script>
console.log("welcome to AIT!");
</script>
</body>
</html>
alert()
- Display Alert BoxThis method displays a popup alert box. It pauses code execution until the user closes the alert.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head> <body> <script>alert("This is an alert box!");
</script>
</body>
</html>
document.write()
- Write Directly to PageWrites content directly to the HTML document, replacing any existing content. Use sparingly, as it can overwrite the page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script>
document.write("Hello from document.write!");
</script>
</body>
</html>
innerHTML
- Insert Content in ElementModifies the content of an HTML element. Ideal for displaying dynamic content within specific parts of the page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<div id="innerHTMLOutput"></div>
<script>
document.getElementById("innerHTMLOutput").innerHTML = "Content updated using innerHTML!";
</script>
</body>
</html>
console.warn()
- Display WarningsThis method outputs warnings in the console, usually styled with a yellow background for easy identification.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script>
console.warn("This is a warning message!");
</script>
</body>
</html>
console.error()
- Display ErrorsThis method displays error messages in the console, usually styled in red for visibility, and useful for catching issues in code.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script>
console.error("This is an error message!");
</script>
</body>
</html>